//
//  DataTransTool.m
//  protobuf-test
//
//  Created by CoderXu on 2017/5/15.
//  Copyright © 2017年 XanderXu. All rights reserved.
//

#import "DataTransTool.h"
static const size_t DEFAULT_BUFFER_SIZE = 4096;

@implementation DataTransTool
//添加开头的长度信息,以便cocket传输使用
+ (void)writeDelimitedTo:(GPBMessage *)proto output:(NSOutputStream *)opStream {
    
    size_t protoSize = proto.serializedSize;
    size_t bufferSize =  [self computePreferredBufferSize:(protoSize + [self computeRawVarint32Size:protoSize])];
    
    NSLog(@"writeDelimitedTo: proto size : %zu", protoSize);
    NSLog(@"writeDelimitedTo: bufferSize size : %zu", bufferSize);
    
    GPBCodedOutputStream *outputStream = [GPBCodedOutputStream streamWithOutputStream:opStream];
    [outputStream writeRawVarintSizeTAs32:protoSize];
    [outputStream writeRawData:[proto data]];
    
    [outputStream flush];
}


+ (size_t)computePreferredBufferSize:(size_t)dataLength {
    if (dataLength > DEFAULT_BUFFER_SIZE) {
        dataLength = DEFAULT_BUFFER_SIZE;
    }
    return dataLength;
}
//计算长度应该用多少位字节表示,以便在cocket通信时在开头加入长度信息
+ (size_t)computeRawVarint32Size:(size_t)value {
    if ((value & (0xffffffff <<  7)) == 0) return 1;
    if ((value & (0xffffffff << 14)) == 0) return 2;
    if ((value & (0xffffffff << 21)) == 0) return 3;
    if ((value & (0xffffffff << 28)) == 0) return 4;
    return 5;
}

@end
